<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="设备名称" prop="deviceId">
        <el-select v-model="queryParams.deviceId" placeholder="请选择设备" clearable filterable>
          <el-option v-for="device in deviceList" :key="device.id" :label="device.deviceName" :value="device.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="维护类型" prop="maintenanceType">
        <el-select v-model="queryParams.maintenanceType" placeholder="请选择维护类型" clearable>
          <el-option v-for="dict in maintenanceTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="维护状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择维护状态" clearable>
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="维护时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['device:maintenance:add']" type="primary" plain icon="Plus" @click="handleAdd">报维修</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['device:maintenance:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <!-- 紧急维护区域 -->
    <el-card class="mb8">
      <template #header>
        <div class="card-header">
          <span>紧急维护</span>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="maintenanceList.filter((item) => item.maintenanceType === 3)"
        row-key="id"
        :max-height="600"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="维护ID" align="center" prop="id" />
        <el-table-column label="设备" align="center" prop="deviceId">
          <template #default="scope">
            <span>{{ scope.row.deviceName || '未知设备' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维护类型" align="center" prop="maintenanceType">
          <template #default="scope">
            <span>{{ maintenanceTypeOptions.find((item) => item.value === scope.row.maintenanceType)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维护状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="维护时间" align="center" width="280">
          <template #default="scope">
            <div>
              <div>开始：{{ scope.row.startTime ? parseTime(scope.row.startTime) : '未开始' }}</div>
              <div>结束：{{ scope.row.endTime ? parseTime(scope.row.endTime) : scope.row.status === 2 ? '已完成' : '维护中' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="维护人员" align="center" prop="userId">
          <template #default="scope">
            <span>{{ scope.row.userName || scope.row.userId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维护结果" align="center" prop="result" />
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 草稿状态 -->
            <template v-if="scope.row.status === 5">
              <el-button type="primary" link @click="handleProcess(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
            <!-- 其他状态 -->
            <el-button v-else type="primary" link @click="handleView(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 故障维修区域 -->
    <el-card class="mb8">
      <template #header>
        <div class="card-header">
          <span>故障维修</span>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="maintenanceList.filter((item) => item.maintenanceType === 2)"
        row-key="id"
        :max-height="600"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="维护ID" align="center" prop="id" />
        <el-table-column label="设备" align="center" prop="deviceId">
          <template #default="scope">
            <span>{{ scope.row.deviceName || '未知设备' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维护类型" align="center" prop="maintenanceType">
          <template #default="scope">
            <span>{{ maintenanceTypeOptions.find((item) => item.value === scope.row.maintenanceType)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维护状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="维护时间" align="center" width="280">
          <template #default="scope">
            <div>
              <div>开始：{{ scope.row.startTime ? parseTime(scope.row.startTime) : '未开始' }}</div>
              <div>结束：{{ scope.row.endTime ? parseTime(scope.row.endTime) : scope.row.status === 2 ? '已完成' : '维护中' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="维护人员" align="center" prop="userId">
          <template #default="scope">
            <span>{{ scope.row.userName || scope.row.userId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维护结果" align="center" prop="result" />
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 草稿状态 -->
            <template v-if="scope.row.status === 5">
              <el-button type="primary" link @click="handleProcess(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
            <!-- 其他状态 -->
            <el-button v-else type="primary" link @click="handleView(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 定期维护区域 -->
    <el-card class="mb8">
      <template #header>
        <div class="card-header">
          <span>定期维护</span>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="maintenanceList.filter((item) => item.maintenanceType === 1)"
        row-key="id"
        :max-height="600"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="维护ID" align="center" prop="id" />
        <el-table-column label="设备" align="center" prop="deviceId">
          <template #default="scope">
            <span>{{ scope.row.deviceName || '未知设备' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维护类型" align="center" prop="maintenanceType">
          <template #default="scope">
            <span>{{ maintenanceTypeOptions.find((item) => item.value === scope.row.maintenanceType)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维护状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="维护时间" align="center" width="280">
          <template #default="scope">
            <div>
              <div>开始：{{ scope.row.startTime ? parseTime(scope.row.startTime) : '未开始' }}</div>
              <div>结束：{{ scope.row.endTime ? parseTime(scope.row.endTime) : scope.row.status === 2 ? '已完成' : '维护中' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="维护人员" align="center" prop="userId">
          <template #default="scope">
            <span>{{ scope.row.userName || scope.row.userId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维护结果" align="center" prop="result" />
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 草稿状态 -->
            <template v-if="scope.row.status === 5">
              <el-button type="primary" link @click="handleProcess(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
            <!-- 其他状态 -->
            <el-button v-else type="primary" link @click="handleView(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewOpen" :title="'查看详情'" width="500px" append-to-body>
      <el-form ref="viewForm" :model="viewForm1" label-width="100px">
        <el-form-item label="维护ID">
          <span>{{ viewForm1.id }}</span>
        </el-form-item>
        <el-form-item label="设备">
          <span>{{ viewForm1.deviceName || '未知设备' }}</span>
        </el-form-item>
        <el-form-item label="维护类型">
          <span>{{ maintenanceTypeOptions.find((item) => item.value === viewForm1.maintenanceType)?.label }}</span>
        </el-form-item>
        <el-form-item label="维护状态">
          <el-tag :type="getStatusType(viewForm1.status)">
            {{ getStatusLabel(viewForm1.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="维护时间">
          <div>
            <div>开始时间：{{ viewForm1.startTime ? parseTime(viewForm1.startTime) : '未开始' }}</div>
            <div>结束时间：{{ viewForm1.endTime ? parseTime(viewForm1.endTime) : viewForm1.status === 2 ? '已完成' : '维护中' }}</div>
          </div>
        </el-form-item>
        <el-form-item label="维护人员">
          <span>{{ viewForm1.userName || viewForm1.userId }}</span>
        </el-form-item>
        <el-form-item label="维护结果">
          <span>{{ viewForm1.result }}</span>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ viewForm1.createTime }}</span>
        </el-form-item>
        <el-form-item label="更新时间">
          <span>{{ viewForm1.updateTime }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getDeviceMaintenanceList,
  getDeviceMaintenance,
  addDeviceMaintenance,
  updateDeviceMaintenance,
  deleteDeviceMaintenance,
  deleteDeviceMaintenanceBatch
} from '@/api/vending/maintenance';
import type { DeviceMaintenanceVO, DeviceMaintenanceQuery } from '@/api/vending/maintenance/types';
import { getlistDevice } from '@/api/vending/device';
import type { DeviceVO } from '@/api/vending/device/types';
import { debounce } from 'lodash-es';
import { getCurrentInstance, ComponentInternalInstance } from 'vue';

const loading = ref(false);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const open = ref(false);
const title = ref('');
const maintenanceList = ref<DeviceMaintenanceVO[]>([]);

// 设备列表相关
const deviceList = ref<DeviceVO[]>([]);
const deviceLoading = ref(false);
const deviceQuery = reactive({
  pageNum: 1,
  pageSize: 20,
  deviceName: '',
  total: 0
});

// 设备数据缓存
const deviceCache = new Map<string, DeviceVO[]>();

// 设备Map用于缓存设备信息
const deviceMap = ref<Map<number, DeviceVO>>(new Map());

const maintenanceTypeOptions = [
  { label: '定期维护', value: 1 },
  { label: '故障维修', value: 2 },
  { label: '紧急维护', value: 3 }
];

// 状态选项
const statusOptions = [
  { value: 0, label: '待维护' },
  { value: 1, label: '维护中' },
  { value: 2, label: '已完成' },
  { value: 3, label: '已退回' },
  { value: 4, label: '已作废' },
  { value: 5, label: '草稿' },
  { value: 6, label: '取消' },
  { value: 7, label: '终止' }
];

const queryParams = reactive<DeviceMaintenanceQuery>({
  pageNum: 1,
  pageSize: 10,
  deviceId: undefined,
  maintenanceType: undefined,
  startTime: [],
  status: undefined
});

const form = reactive<DeviceMaintenanceVO>({
  id: undefined as unknown as number,
  deviceId: undefined as unknown as number,
  maintenanceType: undefined as unknown as number,
  startTime: undefined as unknown as string,
  endTime: undefined as unknown as string,
  userId: undefined as unknown as number,
  userName: undefined as unknown as string,
  maintenanceContent: undefined as unknown as string,
  maintenanceResult: undefined as unknown as string,
  status: undefined as unknown as number,
  remark: undefined as unknown as string,
  createTime: undefined as unknown as string,
  updateTime: undefined as unknown as string,
  maintenanceNo: undefined as unknown as string,
  maintenanceTypeName: undefined as unknown as string,
  statusName: undefined as unknown as string,
  deviceName: undefined as unknown as string,
  result: undefined as unknown as string,
  createBy: '',
  createDept: '',
  updateBy: ''
});

const rules = {
  deviceId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }],
  maintenanceType: [{ required: true, message: '维护类型不能为空', trigger: 'change' }],
  startTime: [{ required: true, message: '维护时间不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '维护人员不能为空', trigger: 'blur' }],
  maintenanceContent: [{ required: true, message: '维护内容不能为空', trigger: 'blur' }]
};

// 添加防抖的查询函数
const debouncedGetList = debounce(() => {
  getList();
}, 300);

/** 获取设备列表 */
async function getDeviceList(query: string = '') {
  if (deviceLoading.value) return; // 防止重复请求

  // 如果有缓存且不是搜索，直接使用缓存
  if (!query && deviceCache.has('default')) {
    deviceList.value = deviceCache.get('default')!;
    return;
  }

  deviceLoading.value = true;
  try {
    const res = await getlistDevice({
      deviceName: query
    });
    if (res && res.code === 200 && Array.isArray(res.data)) {
      deviceList.value = res.data;
      deviceQuery.total = res.data.length;

      // 更新设备Map
      res.data.forEach((device) => {
        if (device && device.id) {
          deviceMap.value.set(device.id, device);
        }
      });

      // 缓存默认列表
      if (!query) {
        deviceCache.set('default', res.data);
      }
    } else {
      deviceList.value = [];
      deviceQuery.total = 0;
    }
  } catch (error) {
    console.error('获取设备列表失败:', error);
    deviceList.value = [];
    deviceQuery.total = 0;
  } finally {
    deviceLoading.value = false;
  }
}

/** 查询设备维护列表 */
async function getList() {
  if (loading.value) return;
  loading.value = true;
  try {
    const response = await getDeviceMaintenanceList(queryParams);
    if (response && response.code === 200 && response.rows) {
      // 按维护类型排序：紧急维护(3) > 故障维修(2) > 定期维护(1)
      maintenanceList.value = response.rows.sort((a, b) => (b.maintenanceType || 0) - (a.maintenanceType || 0));
      total.value = response.total;
    } else {
      ElMessage.error(response?.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取维护列表失败:', error);
    ElMessage.error('获取数据失败，请重试');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 重置表单 */
function reset() {
  const defaultForm: DeviceMaintenanceVO = {
    id: 0,
    deviceId: 0,
    maintenanceType: 0,
    startTime: '',
    endTime: '',
    userId: 0,
    userName: '',
    maintenanceContent: '',
    maintenanceResult: '',
    status: 0,
    remark: '',
    createTime: '',
    updateTime: '',
    maintenanceNo: '',
    maintenanceTypeName: '',
    statusName: '',
    deviceName: '',
    result: '',
    createBy: null,
    createDept: null,
    updateBy: null
  };
  Object.assign(form, defaultForm);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  debouncedGetList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.deviceId = undefined;
  queryParams.maintenanceType = undefined;
  queryParams.startTime = [];
  queryParams.status = undefined;
  debouncedGetList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: any[]) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
async function handleAdd() {
  proxy.$router.push({
    path: '/vending/maintenanceEdit/index',
    query: {
      type: 'add'
    }
  });
}

/** 修改按钮操作 */
async function handleUpdate(row: any) {
  try {
    reset();
    const id = row.id || ids.value[0];
    open.value = true;
    title.value = '修改设备维护';

    // 并行加载所有数据
    const [maintenanceRes] = await Promise.all([
      getDeviceMaintenance(id),
      // 异步加载设备列表
      !deviceCache.has('default')
        ? getDeviceList().then(() => {
            deviceList.value = deviceCache.get('default')!;
          })
        : Promise.resolve().then(() => {
            deviceList.value = deviceCache.get('default')!;
          })
    ]);

    if (maintenanceRes && maintenanceRes.data) {
      Object.assign(form, maintenanceRes.data);
    } else {
      ElMessage.error('获取维护信息失败');
      open.value = false;
    }
  } catch (error) {
    console.error('修改操作失败:', error);
    ElMessage.error('操作失败，请重试');
    open.value = false;
  }
}

/** 提交按钮 */
function submitForm() {
  if (form.id) {
    updateDeviceMaintenance(form).then(() => {
      ElMessage.success('修改成功');
      open.value = false;
      getList();
    });
  } else {
    addDeviceMaintenance(form).then(() => {
      ElMessage.success('新增成功');
      open.value = false;
      getList();
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row: any) {
  const maintenanceIds = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除设备维护编号为"' + maintenanceIds + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (Array.isArray(maintenanceIds)) {
        return deleteDeviceMaintenanceBatch(maintenanceIds);
      } else {
        return deleteDeviceMaintenance(maintenanceIds);
      }
    })
    .then(() => {
      getList();
      ElMessage.success('删除成功');
    });
}

/** 设备选择器远程搜索 - 使用防抖 */
const handleDeviceRemoteSearch = debounce(async (query: string) => {
  if (query) {
    await getDeviceList(query);
  } else {
    // 如果清空搜索，使用缓存数据
    if (deviceCache.has('default')) {
      deviceList.value = deviceCache.get('default')!;
    } else {
      await getDeviceList();
    }
  }
}, 300);

/** 查看详情按钮操作 */
function handleView(row: DeviceMaintenanceVO) {
  proxy.$router.push({
    path: '/vending/maintenanceEdit/index',
    query: {
      type: 'view',
      id: row.id
    }
  });
}

// 定义 viewForm 和 viewOpen
const viewForm1 = ref<DeviceMaintenanceVO>({
  id: 0,
  deviceId: 0,
  maintenanceType: 0,
  startTime: '',
  endTime: '',
  userId: 0,
  userName: '',
  maintenanceContent: '',
  maintenanceResult: '',
  status: 0,
  remark: '',
  createTime: '',
  updateTime: '',
  maintenanceNo: '',
  maintenanceTypeName: '',
  statusName: '',
  deviceName: '',
  result: '',
  createBy: null,
  createDept: null,
  updateBy: null
} as DeviceMaintenanceVO);
const viewOpen = ref(false);

// 优化组件挂载时的数据加载
onMounted(async () => {
  try {
    // 并行加载设备列表和维护列表
    await Promise.all([getDeviceList(), getList()]);
  } catch (error) {
    console.error('初始化数据加载失败:', error);
    ElMessage.error('数据加载失败，请刷新页面重试');
  }
});

// 添加错误处理和重试机制
const retryCount = ref(0);
const maxRetries = 3;

async function retryGetList() {
  if (retryCount.value >= maxRetries) {
    ElMessage.error('数据加载失败，请稍后重试');
    return;
  }
  retryCount.value++;
  await getList();
}

// 添加自动刷新机制（可选）
let refreshTimer: number | null = null;

function startAutoRefresh(interval = 60000) {
  // 默认1分钟刷新一次
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
  refreshTimer = window.setInterval(() => {
    getList();
  }, interval);
}

function stopAutoRefresh() {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
}

// 在组件卸载时清理
onUnmounted(() => {
  stopAutoRefresh();
  debouncedGetList.cancel();
});

// 状态处理函数
const getStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'warning'; // 待维护
    case 1:
      return 'primary'; // 维护中
    case 2:
      return 'success'; // 已完成
    case 3:
      return 'danger'; // 已退回
    case 4:
      return 'info'; // 已作废
    case 5:
      return 'info'; // 草稿
    case 6:
      return 'info'; // 取消
    case 7:
      return 'danger'; // 终止
    default:
      return 'info';
  }
};

const getStatusLabel = (status: number) => {
  switch (status) {
    case 0:
      return '待维护';
    case 1:
      return '维护中';
    case 2:
      return '已完成';
    case 3:
      return '已退回';
    case 4:
      return '已作废';
    case 5:
      return '草稿';
    case 6:
      return '取消';
    case 7:
      return '终止';
    default:
      return '未知状态';
  }
};

// 在 script setup 部分添加处理函数
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const handleProcess = (row: DeviceMaintenanceVO) => {
  proxy.$router.push({
    path: '/vending/maintenanceEdit/index',
    query: {
      type: 'update',
      id: row.id,
      deviceId: row.deviceId,
      deviceName: row.deviceName,
      maintenanceType: row.maintenanceType,
      maintenanceContent: row.maintenanceContent
    }
  });
};
</script>
